package com.ithaixiang.demo.service.impl;

import com.ithaixiang.demo.domian.DataEntity;
import com.ithaixiang.demo.mapper.ExcelMapper;
import com.ithaixiang.demo.service.ExcelService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
@Service
public class ExcelServiceImpl implements ExcelService {
    @Autowired
    ExcelMapper excelMapper;
    @Override
    public String getData(MultipartFile file) {
        try {
            InputStream inputStream =file.getInputStream();
            //获取源文件名
            String fileName = file.getOriginalFilename();
            //获取工作簿
            Workbook workbook = new XSSFWorkbook(inputStream);
            //获取工作表
            Sheet sheet = workbook.getSheetAt(0);
            //获取表中的最后一行的索引
            int lastRowNum = sheet.getLastRowNum();
            //获取单元格列数
            Row row1 = sheet.getRow(0);

            List<DataEntity> dataVos = new ArrayList<>();
            //遍历表中行
            for (int i = 1; i <= lastRowNum; i++) {
                Row sheetRow = sheet.getRow(i);
                //遍历表中行的单元格
                DataEntity dataVo = new DataEntity();
                String kemu = sheetRow.getCell(0).toString();
                //判断第一格数据是否为空，为空不保存
                if (StringUtils.isEmpty(kemu)) {
                    continue;
                }
                String chegnji = sheetRow.getCell(1).toString();
                String xuefen = sheetRow.getCell(2).toString();
                String pass = sheetRow.getCell(3).toString();
                //封装实体类
                dataVo.setKemu(kemu);
                dataVo.setChenji(chegnji);
                dataVo.setXuefen(xuefen);
                dataVo.setPass(pass);
                dataVo.setName(fileName);
                //保存到集合中
                dataVos.add(dataVo);
            }
            //保存数据库
//            dataMapper.savaData(dataVos);
//            dataVos.forEach(x -> {
//                ExcelMapper.insert(x);
//            });
            excelMapper.getData(dataVos);

            System.out.println(dataVos);
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }


}
